package com.dsr.service.impl;

import com.dsr.bean.HomeBean;
import com.dsr.consts.Result;
import com.dsr.dao.ColumnsDao;
import com.dsr.dao.HomepageDao;
import com.dsr.entity.Columns;
import com.dsr.entity.Homepage;
import com.dsr.service.HomepageService;
import com.dsr.util.IdWorker;
import com.dsr.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * (Homepage)表服务实现类
 *
 * @author dsr
 * @since 2020-08-13
 */
@Service("homepageService")
@Transactional
public class HomepageServiceImpl implements HomepageService {
    @Autowired
    private HomepageDao homepageDao;
    @Autowired
    private ColumnsDao columnsDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Result getEntity() {
        if(RedisUtil.getValue("homepage")!=null){
            return Result.success( RedisUtil.getValue("homepage"));
        }
        HomeBean homeBean = new HomeBean();
        List<Homepage> homepages = homepageDao.selectAll();
        if(homepages.size()>0){
            Homepage homepage = homepages.get(0);
            homeBean.setId(homepage.getId());
            homeBean.setNatice(homepage.getNatice());
            homeBean.setImgUrl(Arrays.asList(homepage.getImgUrl().split(",")));
            homeBean.setColumnsList(columnsDao.selectAll());
        }
        RedisUtil.setValue("homepage",homeBean);
        return Result.success(homeBean);
    }

    @Override
    public Result save(HomeBean homeBean) {
        RedisUtil.delete("homepage");
        Homepage homepage = new Homepage();
        homepage.setId(idWorker.nextId() + "");
        homepage.setNatice(homeBean.getNatice());
        homepage.setImgUrl(String.join(",", homeBean.getImgUrl()));
        homepageDao.insert(homepage);
        return insertColmns(homeBean);
    }

    @Override
    public Result update(HomeBean homeBean) {
        RedisUtil.delete("homepage");
        Homepage homepage = new Homepage();
        homepage.setId(homeBean.getId());
        homepage.setNatice(homeBean.getNatice());
        homepage.setImgUrl(String.join(",", homeBean.getImgUrl()));
        homepageDao.updateByPrimaryKeySelective(homepage);
        columnsDao.delete(new Columns());
        return insertColmns(homeBean);

    }
    //TODO insert 优化
    private Result insertColmns(HomeBean homeBean) {
        homeBean.getColumnsList().forEach(item -> {
            if (StringUtils.isEmpty(item.getId()))
                item.setId(idWorker.nextId() + "");
            columnsDao.insert(item);
        });
        return Result.success("保存成功");
    }
}